# -*- coding:utf-8 -*-
import os
import sys
import threading
import signal
import ConfigParser
from gui import MyBrowser
from PyQt4.QtGui import *

from paste.deploy import loadapp
from wsgiref.simple_server import make_server


class Main:

    def __init__(self, *args, **kwargs):
        self._config_file = kwargs.get("config_file", "ses.ini")
        pass

    @staticmethod
    def sigint_handler(signal, frame):
        sys.exit(0)

    @staticmethod
    def start_webservice(configfile):
        cf = ConfigParser.ConfigParser()
        cf.read(configfile)
        host = cf.get("DEFAULT", "host")
        port = cf.get("DEFAULT", "port")

        wsgi_app = loadapp("config:%s" % os.path.abspath(configfile))
        server = make_server(host, int(port), wsgi_app)
        server.serve_forever()

    def __call__(self, *args, **kwargs):
        signal.signal(signal.SIGINT, self.sigint_handler)

        self._webservice = threading.Thread(target=self.start_webservice, args=(self._config_file,), name='web service')
        self._webservice.setDaemon(True)
        self._webservice.start()

        self._app = QApplication(sys.argv)
        browser = MyBrowser()
        browser.show()
        sys.exit(self._app.exec_())


if __name__ == "__main__":
    Main(configfile="ses.ini")()

